package kp.rpc.serializer.factory;

import kp.rpc.serializer.*;
import kp.rpc.spi.SpiLoader;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * 序列化器工厂（用于获取序列化器对象）
 */
@Slf4j
public class SerializerFactory {

    /**
     * 默认的序列化器-jdk序列化器
     */
    private final static Serializer DEFAULT_SERIALIZER = new JdkSerializer();
    private volatile static Map<String, Serializer> MAP = new ConcurrentHashMap<>();

    /**
     * 获取实例-更改为懒汉模式
     *
     * @param key 键
     */
    public static Serializer getInstance(String key) {
        if (MAP.isEmpty()) {
            synchronized (SerializerFactory.class) {
                if (MAP.isEmpty()) {
                    SpiLoader.load(Serializer.class);
                }
                //直接返回key的序列化器
                MAP.putIfAbsent(key, SpiLoader.getInstance(Serializer.class, key));
                return MAP.getOrDefault(key, DEFAULT_SERIALIZER);
            }
        }
        // 不存在key则去SpiLoader中获取
        if (MAP.containsKey(key)) {
            return MAP.get(key);
        }
        MAP.putIfAbsent(key, SpiLoader.getInstance(Serializer.class, key));
        return MAP.getOrDefault(key, DEFAULT_SERIALIZER);
    }
}

